<?php
require("phpsqlajax_dbinfo.php");

function parseToXML($htmlStr) 
{ 
$xmlStr=str_replace('<','&lt;',$htmlStr); 
$xmlStr=str_replace('>','&gt;',$xmlStr); 
$xmlStr=str_replace('"','&quot;',$xmlStr); 
$xmlStr=str_replace("'",'&apos;',$xmlStr); 
$xmlStr=str_replace("&",'&amp;',$xmlStr); 
$xmlStr=str_replace("/",'-',$xmlStr); 
$xmlStr=str_replace(" AM",'Z',$xmlStr); 
$xmlStr=str_replace(" PM",'Z',$xmlStr); 
$xmlStr=str_replace(" ",'T',$xmlStr); 
return $xmlStr; 
} 

// Opens a connection to a mySQL server
$connection=mysql_connect ("localhost", $username, $password);
if (!$connection) {
  die('Not connected : ' . mysql_error());
}

// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ('Can\'t use db : ' . mysql_error());
}

// Select all the rows in the gdlh table
$query = "SELECT * FROM (SELECT * FROM gdlh WHERE DEVICE_ID = 2 and GPS_TIME >= '11/23/2007' and PK_INDEX >= 3307 ORDER BY GPS_TIME desc LIMIT 200) a ORDER BY PK_INDEX";
$result = mysql_query($query);
if (!$result) {
  die('Invalid query: ' . mysql_error());
}

// XML Header to expire the content Date in the past
header("Expires: Mon, 1 Jan 2007 05:00:00 GMT"); 
// always modified
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
// HTTP/1.1
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
// HTTP/1.0
header("Pragma: no-cache");
//XML Header
header("Content-type: text/xml");

// Start XML file, echo parent node
echo '<History>';
echo '<Run>';
echo '<Track>';

// Iterate through the rows, printing XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  // ADD TO XML DOCUMENT NODE
  echo '<Trackpoint>';
  echo '<Position>';
  echo '<Latitude>';
  echo '' . $row['LAT'] . ' ';
  echo '</Latitude>';
  echo '<Longitude>';
  echo '' . $row['LON'] . ' ';
  echo '</Longitude>';
  echo '<Altitude>';
  echo '' . $row['ALT'] . ' ';
  echo '</Altitude>';
  echo '</Position>';
  echo '<Time>';
  echo '' . parseToXML($row['GPS_TIME']) . ' ';
  echo '</Time>';  
  echo '</Trackpoint>';
  }

// End XML file
echo '</Track>';
echo '</Run>';
echo '</History>';

?>